<template>
    <el-dialog :close-on-click-modal="false" ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible"
        width="50%" :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
            :class="foldDialog ? 'demo-ruleForm' : ''">
            <el-form-item label="养殖设施" prop="facilityId">
                <el-select v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施" @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
            </el-form-item>
            <el-form-item label="物料名称" prop="materialNo">
                <el-select v-model="ruleForm.materialNo" class="w100p" clearable filterable placeholder="请选择物料"
                    @change="querymaterialName">
                    <el-option v-for="item, index in materialList" :key="index" :label="item.materialName"
                        :value="item.materialNo"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="选择出库单" prop="outboundOrderIdList" v-if="storageRules == 'THREE'">
                <el-select clearable filterable class=" w100p" v-model="ruleForm.outboundOrderIdList"
                    placeholder="请选择出库单" @change="getOutboundOrder($event)" multiple>
                    <el-option v-for="order, index in outboundOrder" :key="index"
                        :disabled="ruleForm.materialNo !== order.materialNo"
                        :label="`仓库名称：${order.stordocName}；物料名称：${order.materialName};出库单号：${order.outboundOrderNo}`"
                        :value="order.outboundOrderId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="物料数量" prop="amount">
                <el-input type="number" v-model="ruleForm.amount" placeholder="请输入参数"
                    :disabled="storageRules == 'THREE'">
                    <template slot="append">{{ unitName }}</template>
                </el-input>
            </el-form-item>
            <el-form-item label="操作人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="handleChangePerson">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上传凭证" prop="fileIdList">
                <UpLoadImage v-if="dialogVisible" @getFileIdList="getFileIdList" :idList="fileIdList" :limit="5">
                </UpLoadImage>
            </el-form-item>
            <el-form-item label="备注">
                <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="ruleForm.remark" :minlength="50"
                    show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="投入日期" prop="inputDate">
                <el-date-picker v-model="ruleForm.inputDate" value-format="yyyy-MM-dd" align="right" type="date"
                    placeholder="选择日期" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <div class="foldDialog" @click="foldDialog = !foldDialog">
            <i :class="foldDialog ? 'el-icon-caret-bottom' : 'el-icon-caret-top'"></i> {{ foldDialog ? '展开' : '收起' }}
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import UpLoadImage from "@/components/UpLoadImage";
import materialInputRecord from '@/api/inputManagment/materialInputRecord.js';
import outStorage from "@/api/livestock-manage/sale-manage/out-storage"; // 出库
export default {
    components: { UpLoadImage },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
        person: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            storageRules: '',
            outboundOrder: [],
            foldDialog: true,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            unitName: '',
            fileIdList: [],
            rules: {
                facilityId: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                materialNo: [
                    { required: true, message: '请选择物料', trigger: 'change' }
                ],
                amount: [
                    { required: true, message: '请输入数量', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                inputDate: [
                    { required: true, message: '请选择投塘日期', trigger: 'change' }
                ],
                outboundOrderIdList: [
                    { required: true, message: "请选择出库单", trigger: ["change", "blur"] }
                ],
            }
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
            this.storageRules = sessionStorage.storageRules
        }
    },

    mounted() { },
    methods: {
        initData() {
            this.foldDialog = true;
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.ruleForm = {}
                this.addEditApi = materialInputRecord.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId,
                    fileIdList: this.data.fileIdList ? this.data.fileIdList.split(",") || [] : []
                }
                this.addEditApi = materialInputRecord.edit
                this.addEditName = '编辑'
                this.fileIdList = this.data.fileIdList ? this.data.fileIdList.split(",") || [] : []
                this.querymaterialName(this.data.materialNo)
            }
            this.$set(this.ruleForm, 'outboundOrderIdList', this.ruleForm.outOrderIds ? this.ruleForm.outOrderIds.split(',') : []);
            let outboundOrderIds = this.ruleForm.outboundOrderIdList;
            this.getConditionQuery(outboundOrderIds);
        },
        async getConditionQuery(outboundOrderIds = []) {
            let { data } = await outStorage.conditionQuery({ outboundOrderType: 1, relatedProduction: false, outboundOrderIds });
            this.outboundOrder = data || []
            console.log(data)
        },
        getOutboundOrder(list) {
            let orderList = this.outboundOrder.filter(e => {
                return list.includes(e.outboundOrderId)
            })
            console.log(orderList, list)
            let amount = orderList.reduce((sum, item) => sum + item.confirmQuantity, 0);
            this.$set(this.ruleForm, 'amount', amount)
        },
        getFileIdList(data) {
            this.$set(this.ruleForm, 'fileIdList', data.fileIdList || [])
        },
        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
            // this.queryByConditionPondInfo(this.ruleForm.batchId)
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            console.log(result)
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchId', '');
            this.$set(this.ruleForm, 'batchName', '');
        },
        querymaterialName(no) {
            let result = this.materialList.find(obj => obj.materialNo == no);
            console.log(result)
            result.materialNo && this.$set(this.ruleForm, 'materialName', result.materialName)
            this.unitName = result.unitName || '斤'
            this.$set(this.ruleForm, 'unitName', result.unitName || '斤');
            console.log(this.ruleForm)
        },
        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    console.log(this.ruleForm.fileIdList)
                    let fileIdList = this.ruleForm.fileIdList
                    this.addEditApi({ ...this.ruleForm, status: 'APPROVAL', fileIdList: fileIdList ? this.ruleForm.fileIdList.join(',') : '' }).then(res => {
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '操作成功' : res.msg)
                        let id = res.data?.materialRecordId;
                        this.approved(id)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        async approved(id) {
            if (id) {
                let { code } = await materialInputRecord.approved(id)
                if (code == 1) {
                    this.cancel();
                }
            }
        },
        //重置
        resetForm() {
            this.fileIdList = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>

<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}

.foldDialog {
    width: 100%;
    line-height: 50px;
    background-color: #ffffff;
    position: absolute;
    bottom: 0;
    left: 0;
    padding: 0 20px;
    text-align: right;
    box-shadow: 0 -10px 10px 0px rgba(0, 21, 41, 0.1);
    cursor: pointer;
}

.demo-ruleForm {
    height: 400px;
    margin-bottom: 50px;
    overflow: auto;
}
</style>